package com.sk.weichat.adapter;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.audio_x.VoiceAnimView;
import com.sk.weichat.audio_x.VoicePlayer;
import com.sk.weichat.bean.circle.PublicMessage;
import com.sk.weichat.bean.collection.CollectionEvery;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.GetFileSizeUtil;
import com.sk.weichat.util.HtmlUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.util.link.HttpTextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JVCideoPlayerStandardSecond;

public class MyCollectionAdapter extends BaseMultiItemQuickAdapter<CollectionEvery, BaseViewHolder> {

    //static SimpleDateFormat sdf = new SimpleDateFormat("YY-dd hh:mm");

    public MyCollectionAdapter(List<CollectionEvery> data) {
        super(data);
        //必须绑定type和layout的关系
        addItemType(CollectionEvery.TYPE_IMAGE, R.layout.item_collection_img);
        addItemType(CollectionEvery.TYPE_FILE, R.layout.item_collection_document);
        addItemType(CollectionEvery.TYPE_TEXT, R.layout.item_collection_text);
        addItemType(CollectionEvery.TYPE_VIDEO, R.layout.item_collection_video);
        addItemType(CollectionEvery.TYPE_VOICE, R.layout.item_collection_voice);
        addItemType(CollectionEvery.TYPE_LINK, R.layout.item_collection_link);
    }

    @Override
    protected void convert(BaseViewHolder holder, CollectionEvery item) {
        holder.addOnClickListener(R.id.iv_check, R.id.tv_delete, R.id.iv_avatar, R.id.tv_name, R.id.iv_image, R.id.tv_bg, R.id.iv_doc_type_icon, R.id.tv_doc_name, R.id.tv_doc_size, R.id.view_mask);
        //昵称
        holder.setText(R.id.tv_name, item.getFromNickName());
        if (item.isChecked) {
            holder.setImageResource(R.id.iv_check, R.mipmap.icon_checked);
        } else {
            holder.setImageResource(R.id.iv_check, R.mipmap.icon_checkedbox_normal);
        }
        ImageView ivCheck = holder.getView(R.id.iv_check);
        //用户头像
        ImageView ivAvatar = holder.getView(R.id.iv_avatar);
        //AvatarHelper.getInstance().displayAvatar(item.getToUserId() + "", ivAvatar);
        String url = AvatarHelper.getInstance().getAvatarUrl(item.getFromUserId() + "", true);
        // Log.e("lzs", "url:" + url + "  userid:" + item.getToUserId());
        loadImg(url, ivAvatar);
        //设置时间
        holder.setText(R.id.tv_time, TimeUtils.getFriendlyTimeDesc(mContext, (int) item.getCreateTime()));
        if (item.isEdit) {
            ivCheck.setVisibility(View.VISIBLE);
        } else {
            ivCheck.setVisibility(View.GONE);
        }

        TextView tvDelete = holder.getView(R.id.tv_delete);
        if (item.deleteAble) {
            tvDelete.setVisibility(View.VISIBLE);
        } else {
            tvDelete.setVisibility(View.GONE);
        }
        //

        switch (holder.getItemViewType()) {
            case CollectionEvery.TYPE_IMAGE:
                convertImageItem(holder, item);
                break;
            case CollectionEvery.TYPE_FILE:
                convertFileItem(holder, item);
                break;
            case CollectionEvery.TYPE_TEXT:
                convertTextItem(holder, item);
                break;
            case CollectionEvery.TYPE_VIDEO:
                convertVideoItem(holder, item);
                break;
            case CollectionEvery.TYPE_VOICE:
                convertVoiceItem(holder, item);
                break;

            case CollectionEvery.TYPE_LINK:
                convertLinkItem(holder, item);
                break;
        }
    }

    private void convertTextItem(BaseViewHolder holder, CollectionEvery item) {
        String msg = item.getMsg();
        HttpTextView httpTextView = (HttpTextView) holder.getView(R.id.tv_content);
        // 支持emoji显示
        String content = StringUtils.replaceSpecialChar(msg);
        CharSequence charSequence = HtmlUtils.transform200SpanString(content.replaceAll("\n", "\r\n"), true);
        httpTextView.setUrlText(charSequence);
        httpTextView.setToUserId(item.getUserId());
    }

    private void convertLinkItem(BaseViewHolder holder, CollectionEvery item) {
        TextView content = (TextView) holder.getView(R.id.tv_content);
        Drawable drawableLeft = mContext.getResources().getDrawable(R.mipmap.img_link);
        content.setText(item.getUrl());
        drawableLeft.setBounds(0, 0, drawableLeft.getIntrinsicWidth(), drawableLeft.getIntrinsicHeight());
        content.setCompoundDrawables(drawableLeft, null, null, null);
        content.setCompoundDrawablePadding(ViewPiexlUtil.dp2px(mContext, 12));
    }

    private void convertVoiceItem(BaseViewHolder holder, CollectionEvery item) {
        VoiceAnimView voiceAnimView = holder.getView(R.id.view_voice);
        PublicMessage publicMessage = new PublicMessage();
        publicMessage.setMessageId(item.getEmojiId());
        PublicMessage.Body body = new PublicMessage.Body();
        body.setType(PublicMessage.TYPE_VOICE);
        List<PublicMessage.Resource> audios = new ArrayList<>();
        PublicMessage.Resource resource = new PublicMessage.Resource();
        resource.setLength(item.getFileLength());
        resource.setSize(item.getFileSize());
        resource.setOriginalUrl(item.getUrl());
        audios.add(resource);
        body.setAudios(audios);
        publicMessage.setBody(body);
        voiceAnimView.fillData(publicMessage);
        //重新设置动画背景
        voiceAnimView.setSeekBarBackground(true);
        voiceAnimView.setLeftAnimRes(R.drawable.voice_play_right);
        voiceAnimView.resetAnim();
        voiceAnimView.setTvTimeTextColor(Color.WHITE);
        voiceAnimView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VoicePlayer.instance().playVoice(voiceAnimView);
            }
        });


    }

    private void convertVideoItem(BaseViewHolder holder, CollectionEvery item) {
        JVCideoPlayerStandardSecond videoView = (JVCideoPlayerStandardSecond) holder.getView(R.id.iv_video);
        videoView.setUp(item.getUrl(),
                JVCideoPlayerStandardSecond.SCREEN_LAYOUT_NORMAL, "");
        videoView.addChatClicklistener(new JCVideoPlayer.JVOnClicklistener() {
            @Override
            public void onClick() {
                VoicePlayer.instance().stop();
            }

            @Override
            public void onLongClick() {
            }
        });
        AvatarHelper.getInstance().asyncDisplayOnlineVideoThumb(item.getUrl(), videoView.thumbImageView);
    }

    private void convertFileItem(BaseViewHolder holder, CollectionEvery item) {
        String fileName = item.getFileName();
        String type = "";
        try {
            type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        } catch (Exception e) {
        }
        if (type.equals("jpg") || type.equals("jpeg") || type.equals("png")) {
            Glide.with(mContext).load(item.getUrl()).centerCrop().placeholder(R.mipmap.default_error).error(R.mipmap.default_error).into((ImageView) holder.getView(R.id.iv_doc_type_icon));
        } else {
            AvatarHelper.getInstance().fillFileView(type, holder.getView(R.id.iv_doc_type_icon));
        }

        String filename = "";
        try {
            fileName = item.getFileName().substring(item.getFileName().lastIndexOf("/") + 1);
        } catch (Exception e) {

        }
        holder.setText(R.id.tv_doc_name, fileName);
        //文档大小
        String sizeStr = GetFileSizeUtil.formatFileSize(item.getFileSize());
        holder.setText(R.id.tv_doc_size, sizeStr);

    }

    private void convertImageItem(BaseViewHolder holder, CollectionEvery item) {
        loadImg(item.getUrl(), holder.getView(R.id.iv_image));
    }

    private void loadImg(String url, ImageView imageView) {
        Glide.with(MyApplication.getContext())
                .load(url)
                .placeholder(R.drawable.avatar_normal)
                .dontAnimate()
                .error(R.drawable.avatar_normal)
                .into(imageView);
    }

}
